package com.jgads.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import com.anythink.banner.unitgroup.api.CustomBannerAdapter;
import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.junion.ad.BannerAd;
import com.junion.ad.bean.BannerAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.BannerAdListener;

import java.util.Map;

/**
 * @author songzi
 * @date 2021/12/6
 */
public class BannerAdapter extends CustomBannerAdapter {
    private String slotId;
    private boolean isBidding;
    private BannerAd bannerAd;
    private View mBannerView;
    private BannerAdInfo mBannerAdInfo;
    private ATBiddingListener biddingListener;


    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtras) {
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String s) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", s);
                        }
                    }
                });


    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }

        InitManager.getInstance().
                initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        String name = Thread.currentThread().getName();
                        Log.e("wsong", "name = " + name);
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String msg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", msg);
                        }
                    }
                });
        return true;
    }

    private void startLoad(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (context == null) {
                    if (isBidding) {
                        if (biddingListener != null) {
                            biddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.fail("context is null"),
                                    null);
                        }
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1", "context is null");
                        }
                    }
                    return;
                }

                bannerAd = new BannerAd(context);
                bannerAd.setListener(new BannerAdListener() {
                    @Override
                    public void onAdExpose(BannerAdInfo adInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdShow();
                        }
                    }

                    @Override
                    public void onAdClick(BannerAdInfo adInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdClicked();
                        }
                    }

                    @Override
                    public void onAdClose(BannerAdInfo adInfo) {
                        if (mImpressionEventListener != null) {
                            mImpressionEventListener.onBannerAdClose();
                        }
                    }

                    @Override
                    public void onAdReceive(BannerAdInfo adInfo) {
                        mBannerAdInfo = adInfo;
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfo != null && adInfo.getBidPrice() > 0) {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.success(
                                                    adInfo.getBidPrice()
                                                    , adInfo.getKey()
                                                    , null
                                                    , ATAdConst.CURRENCY.RMB_CENT)
                                            , null);
                                } else {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo is null"),
                                            null);
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdCacheLoaded();
                            }
                        }
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(error.getError())
                                        , null
                                );
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError(
                                        "" + error.getCode()
                                        , "" + error.getError()
                                );
                            }
                        }
                    }
                });
                bannerAd.loadAd(slotId);
            }
        });


    }

    @Override
    public void destory() {
        if (bannerAd != null) {
            releaseLoadResource();
            bannerAd.release();
            bannerAd = null;
        }
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    @Override
    public View getBannerView() {
        if (mBannerAdInfo != null) {

            mBannerView = mBannerAdInfo.getAdView();
            mBannerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    try {

                        if (mBannerView != null && mBannerView.getParent() != null) {
                            int width = ((ViewGroup) mBannerView.getParent()).getMeasuredWidth();
                            if (mBannerView.getLayoutParams().width != width) {
                                mBannerView.getLayoutParams().width = -1;
                                mBannerView.getLayoutParams().height = -1;
                                ((ViewGroup) mBannerView.getParent()).requestLayout();
                                mBannerView.getViewTreeObserver().removeOnPreDrawListener(this);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            });
            mBannerAdInfo.render();
        }


        return mBannerView;

    }

}
